# !/usr/bin python3
# encoding: utf-8 -*-
# @file     : mock_server.py
# @author   : 沙陌 Matongxue_2
# @Time     : 2023/8/19 14:39
# @Copyright: 北京码同学
import time

import requests.exceptions
from flask import Flask, request, make_response

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello world'


# 定义一个get接口，没有参数的
@app.route('/get')  # /get其实就是接口路径
def get():
    return '这是get接口'


# 有参数的get接口
@app.route('/get/params')
def get_params():
    id = request.args.get('id')  # 获取请求参数id
    return f'你传的参数id是{id}'


# 参数为表单类型的post接口
@app.route('/post/form', methods=['POST'])  # methods定义了接口支持的请求方式
def post_form():
    # 有参数的接口 ?username=2&password=2
    username = request.form.get('username')
    password = request.form.get('password')
    return f'欢迎{username},密码是{password}'


# 参数为json类型的post接口
@app.route('/post/json', methods=['POST'])
def post_json():
    username = request.json['username']
    password = request.json['password']
    return {'status': 0, 'message': 'success'}


# 有路径参数的put或者delete请求
@app.route('/put/<id>/change', methods=['PUT'])
def change_data(id):
    return f'{id}数据修改成功'


@app.route('/delete/<id>', methods=['DELETE'])
def delete_data(id):
    return f'{id}数据删除成功'


# 返回异常的状态码
@app.route('/return/statuscode', methods=['POST'])
def return_statuscode():
    resp = make_response()  # 造一个响应对象
    resp.status_code = 500
    return resp


# 响应延迟
@app.route('/delay')
def delay():
    time.sleep(10)
    return '延迟了10秒后得到的结果'


# 网络中断
@app.route('/interrupt')
def interrupt():
    raise requests.exceptions.ConnectionError('Network connection Error')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8006)
